package com.discovery.util;


/**
 * @Author xuebinlu
 * @Date 2018/5/16 9:42
 * @Version 1.0
 * @Description XML与java实例之间的数据格式转换工具类
 **/

import com.discovery.constant.ProjectConstant;

import javax.xml.bind.*;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 使用Jaxb2.0实现XML<->Java Object的Binder.
 * <p>
 * 特别支持Root对象是List的情形.
 *
 * @author xuebinlu
 */
public class JaxbUtil {
    //由于JAXB是线程安全的，JAXBContext可以多线程使用。但是由于创建JAXBContext是比较消耗性能的，所以这里做cache，重复使用。
    private static Map<Class<?>, JAXBContext> contextMap = new ConcurrentHashMap<>();

    /**
     * @param type 需要转换的java对象
     */
    public static JAXBContext getJaxbContext(Class<?> type) {
        return contextMap.computeIfAbsent(type, k -> {
            try {
                return JAXBContext.newInstance(type);
            } catch (JAXBException e) {
                throw new RuntimeException(e);
            }
        });
    }

    /**
     * Java Object->Xml.
     */
    public static String toXml(Object root, String encoding) {
        try {
            StringWriter writer = new StringWriter();
            createMarshaller(root.getClass(),encoding).marshal(root, writer);
            return writer.toString();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Java Object->Xml, 特别支持对Root Element是Collection的情形.
     */
    @SuppressWarnings("unchecked")
    public String toXml(Collection root, String rootName, Class<?> type,String encoding) {
        try {
            CollectionWrapper wrapper = new CollectionWrapper();
            wrapper.collection = root;

            JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(
                    new QName(rootName), CollectionWrapper.class, wrapper);

            StringWriter writer = new StringWriter();
            createMarshaller(type,encoding).marshal(wrapperElement, writer);

            return writer.toString();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Xml->Java Object.
     */
    @SuppressWarnings("unchecked")
    public <T> T fromXml(Class<?> type,String xml) {
        try {
            StringReader reader = new StringReader(xml);
            return (T) createUnmarshaller(type).unmarshal(reader);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Xml->Java Object, 支持大小写敏感或不敏感.
     */
    public <T> T fromXml(Class<?> type,String xml, boolean caseSensitive) {
        try {
            String fromXml = xml;
            if (!caseSensitive) {
                fromXml = xml.toLowerCase(new Locale(ProjectConstant.ENCODING_UTF8));
            }
            StringReader reader = new StringReader(fromXml);
            return (T) createUnmarshaller(type).unmarshal(reader);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建Marshaller, 设定encoding(可为Null).
     */
    public static Marshaller createMarshaller(Class<?> type,String encoding) {
        try {
            JAXBContext jaxbContext = JaxbUtil.getJaxbContext(type);
            Marshaller marshaller = jaxbContext.createMarshaller();

            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            if (!StringUtils.isBlank(encoding)) {
                marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            }
            return marshaller;
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建UnMarshaller.
     */
    public Unmarshaller createUnmarshaller(Class<?> type) {
        try {
            JAXBContext jaxbContext = JaxbUtil.getJaxbContext(type);
            return jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 封装Root Element 是 Collection的情况.
     */
    public static class CollectionWrapper {
        @SuppressWarnings("unchecked")
        @XmlAnyElement
        Collection collection;
    }

    public static String convertToXml(Object obj) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //编码格式
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);// 是否省略xm头声明信息

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        marshaller.marshal(obj, baos);
        return new String(baos.toByteArray());// 生成XML字符串
    }
}  